package vn.com.pavibook.daoImpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import vn.com.pavibook.dao.PersonDao;
import vn.com.pavibook.domain.model.PagingInfo;
import vn.com.pavibook.domain.model.Person;
import vn.com.pavibook.domain.model.SearchResult;
import vn.com.pavibook.utils.DaoHelper;

@Repository
public class PersonDaoImpl extends DaoHelper<Person> implements PersonDao{
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Person> getListPerson() {
		PagingInfo pagingInfo = new PagingInfo(10, 1);
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT * FROM Person");
		List<Person> result = new ArrayList<Person>();
		SearchResult<Person> searchResult = queryPaging(sql.toString(), null, new PersonRowMapper(), pagingInfo);
//		SearchResult<Person> searchResult = query(sql.toString(), new PersonRowMapper());
		result = searchResult.getSearchResult();
		return result;
	}
	
	
	@SuppressWarnings("rawtypes")
	class PersonRowMapper implements RowMapper{
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			Person person = new Person();
			person.setId(rs.getInt("id"));
			person.setName(rs.getString("name"));
			person.setAge(rs.getInt("age"));
			return person;
		}
	}

	@Override
	public void insert(Person person) {
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO Person (name, age) VALUES (?, ?)");
		Object[] parameters = new Object[]{person.getName(), person.getAge()};
		insert(sql.toString(), parameters);
	}
	
}
